package yhp.com.zijie.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class WebFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);

        //查看session中是否有值，防止用户未登录情况下直接访问
        Object users = request.getSession().getAttribute("users");

        if (requestURI.endsWith("/") && users==null){
//            response.sendRedirect("login.jsp");
            PrintWriter writer = response.getWriter();
            writer.println("<script>location.href='login.jsp';alert('请先登录');</script>");
        }


        filterChain.doFilter(servletRequest , servletResponse);
    }

    @Override
    public void destroy() {

    }
}
